package com.shisfish.library.Timing;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import com.shisfish.library.Impl.ArrearageBookImpl;
import com.shisfish.library.Impl.BookLendImpl;
import com.shisfish.library.Impl.UserImpl;
import com.shisfish.library.Model.ArrearageBook;
import com.shisfish.library.Model.BookLend;
import com.shisfish.library.Model.User;

public class ArrearBook extends TimerTask {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		// 找过所有未归还的
				List<BookLend> bookLends = new BookLendImpl().selectNotReturn();
				if (bookLends.size() > 0) {
					
					for (int i = 0, len = bookLends.size(); i < len; i++) {
						BookLend bookLend = bookLends.get(i);
						// 查看arrearage_book中有木有该信息，有则修改，无则添加
						
						String barCode = bookLend.getBarCode();
						String employee = bookLend.getBorrower();
						ArrearageBook arrearageBook = new ArrearageBookImpl().selectByBM(barCode, employee);
						List<User> users = new UserImpl().selectByKey(employee);
						if (users.size() > 0) {
							BigDecimal arrearage = users.get(0).getUserLevel().getArrearage();
							
							if (arrearage.compareTo(new BigDecimal(0)) == 1) {
								if (arrearageBook != null) {
									// 已有数据 添加当前的用户欠费金额
									Date lastTime = arrearageBook.getLastTime();
									
									Calendar cal = Calendar.getInstance();
									
									cal.setTime(lastTime);
									
									int lastDay = cal.get(Calendar.DAY_OF_YEAR);
									
									cal.setTime(new Date());
									
									int nowDay = cal.get(Calendar.DAY_OF_YEAR);
									
									int days = nowDay - lastDay;
									
									// 如果不是同一天，才计算钱
									if (days > 0) {
										BigDecimal arrearage_now = arrearage.multiply(new BigDecimal(days));
										
										BigDecimal arrearage_last = arrearage_now.add(arrearageBook.getArrearage());
										
										arrearageBook.setArrearage(arrearage_last);
										arrearageBook.setLastTime(new Date());
										
										new ArrearageBookImpl().updateOne(arrearageBook);
									}
									
								} else {

									// 没有数据，新增数据
									
									Date shouldReturnTime = bookLend.getShouldReturnTime();
									
									Calendar cal = Calendar.getInstance();
									
									cal.setTime(shouldReturnTime);
									
									int lastDay = cal.get(Calendar.DAY_OF_YEAR);
									
									cal.setTime(new Date());
									
									int nowDay = cal.get(Calendar.DAY_OF_YEAR);
									
									int days = nowDay - lastDay;
									
									if (days > 0) {
										BigDecimal arrearage_last = arrearage.multiply(new BigDecimal(days));
										
										ArrearageBook arrearageBook1 = new ArrearageBook(barCode, employee, shouldReturnTime, new Date(), arrearage_last);
										
										new ArrearageBookImpl().insertOne(arrearageBook1);
									}
									
								}
								
							}
						}
						
					}
					
				}
	}

}
